/**
 * @BelongsProject: hmall-micro
 * @BelongsPackage: com.hmall.cart.listener
 * @Author: 王明天
 * @CreateTime: 2025/2/15 0:01
 * @Description: CartClearListener
 */
package com.hmall.cart.listener;


import com.hmall.api.item.dto.ItemDTO;
import com.hmall.cart.service.ICartService;
import com.hmall.common.constants.MQConstants;
import com.hmall.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class CartClearListener {

    private final ICartService cartService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.TRADE_CLEAR_QUEUE_NAME),
            exchange = @Exchange(name = MQConstants.TRADE_EXCHANGE_NAME),
            key = MQConstants.TRADE_CLEAR_ROUTING_KEY
    ))
    public void listenCartClear(Collection<ItemDTO> items, Message message) {

        Long userId = message.getMessageProperties().getHeader("userId");
        List<Long> itemsIds = new ArrayList<>();

        items.forEach(item -> {
            itemsIds.add(item.getId());
        });

        if (itemsIds.isEmpty()) {
            return;
        }

        cartService.removeByItemIds(userId,itemsIds);

        log.info("清空购物车成功");

    }

}
